# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#   PROYECCIONES DE POBLACIÓN
#   TABULADOS A NIVEL PROVINCIAL
#   TABULADO DE INDICADORES DEMOGRÁFICOS A MITAD DE AÑO
#   POBLACIÓN POR PROVINCIA, EDAD Y SEXO
#
#   Elaborado por: Alexander Oviedo
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

# =========================================================
# 1. LIMPIEZA DEL ENTORNO
# =========================================================
rm(list = ls())
gc()

# =========================================================
# 2. LIBRERÍAS
# =========================================================
library(tidyverse)
library(openxlsx)
library(readxl)
library(data.table)
library(janitor)

options(scipen = 999)
Sys.setenv("R_ZIPCMD" = "C:/Rtools/bin/zip.exe")

# =========================================================
# 3. FUNCIONES DE REDONDEO (ROBUSTAS)
# =========================================================

# Redondeo general (2 decimales)
redondear_2 <- function(dt) {
  cols_num <- names(dt)[sapply(dt, is.numeric)]
  dt[, (cols_num) := lapply(.SD, round, 2), .SDcols = cols_num]
  return(dt)
}

# Redondeo especial (1 decimal)
redondear_1 <- function(dt) {
  cols_num <- names(dt)[sapply(dt, is.numeric)]
  dt[, (cols_num) := lapply(.SD, round, 1), .SDcols = cols_num]
  return(dt)
}

# =========================================================
# 4. INDICADORES DE ESTRUCTURA
# =========================================================
ind_est <- fread("bdd/bdd_indicad_demogr_prov.csv")
ind_est <- ind_est[, c(2:3,10,8,9,7)]

ind_est_f <- split(ind_est, ind_est$prov)

ind_est_f <- lapply(ind_est_f, function(x) {
  
  dt <- pivot_longer(
    x, c(3:6),
    names_to = "indicador",
    values_to = "value"
  ) %>%
    pivot_wider(names_from = "year", values_from = "value") %>%
    setDT()
  
  # 🔹 REDONDEO REAL
  dt <- redondear_2(dt)
  
  # Solo presentación
  dt <- dt[, c(3:63)]
  return(dt)
})

# =========================================================
# 5. PLANTILLA
# =========================================================
planti <- loadWorkbook("bdd/plantilla/Plantilla_indica_demogra.xlsx")
sheet <- names(planti)
sheet1 <- sheet[2:25]

for (i in seq_along(ind_est_f)) {
  writeData(planti, sheet = sheet1[[i]],
            x = ind_est_f[[i]],
            startRow = 12, startCol = 3,
            colNames = FALSE, rowNames = FALSE)
}

# =========================================================
# 6. COMPONENTES DEMOGRÁFICOS
# =========================================================
comp <- fread("bdd/nac_def_smn_cuadre.csv")

comp <- pivot_wider(comp,
                    names_from = "indicador",
                    values_from = "redonder") %>%
  setDT()

arch_prov <- list.files("bdd/1_prov", pattern = "*.xlsx", full.names = TRUE)

bases <- lapply(arch_prov, read_excel,
                sheet = "resumen", range = "A4:BJ32") %>%
  lapply(setDT)

for (i in seq_along(bases)) {
  bases[[i]][["1990"]] <- as.numeric(bases[[i]][["1990"]])
}

bases <- lapply(bases, function(x)
  pivot_longer(x[c(19,26:28)], c(2:62),
               names_to = "year", values_to = "values") %>%
    setDT()
)

base_f <- rbindlist(
  lapply(seq_along(bases), function(i) {
    bases[[i]][, prov := i]
  })
)

base_f <- pivot_wider(base_f,
                      names_from = "Indicadores Demográficos",
                      values_from = "values")

base_f$year <- as.numeric(base_f$year)

comp <- merge(comp, base_f, by = c("year","prov"), all.x = TRUE)

# =========================================================
# 7. ESPERANZA DE VIDA (1 DECIMAL)
# =========================================================
tab_vid <- fread("bdd/lt_ecu_prov_x1_1990_2050.csv")[age=="0", c(1:4,13)]
tab_vid_as <- fread("bdd/lt_ecu_prov_x1_both_1990_2050.csv")[age=="0", c(1:4,11)]

tab_vidf <- rbind(tab_vid, tab_vid_as)

tab_vidf <- tab_vidf[,-"age"] %>%
  pivot_wider(names_from = "sex", values_from = "ex") %>%
  setDT() %>%
  setnames(c("m","f","b"), c("Hombre","Mujer","Ambos"))

comp <- merge(comp, tab_vidf, by = c("year","prov"), all.x = TRUE)

# =========================================================
# 8. FECUNDIDAD (2 DECIMALES)
# =========================================================
fec <- comp[,c(1,2,3,7,6)] %>%
  pivot_longer(c(3:5), names_to = "indicador", values_to = "value") %>%
  pivot_wider(names_from = "year", values_from = "value") %>%
  setDT()

fec <- redondear_2(fec)
fec <- split(fec, fec$prov)
fec <- lapply(fec, function(x) x[,-c(1,2)])

for (i in seq_along(fec)) {
  writeData(planti, sheet = sheet1[[i]],
            x = fec[[i]],
            startRow = 17, startCol = 3,
            colNames = FALSE, rowNames = FALSE)
}

# =========================================================
# 9. MORTALIDAD (2 DECIMALES)
# =========================================================
mort <- comp[,c(1,2,4,8)] %>%
  pivot_longer(c(3:4), names_to = "indicador", values_to = "value") %>%
  pivot_wider(names_from = "year", values_from = "value") %>%
  setDT()

mort <- redondear_2(mort)
mort <- split(mort, mort$prov)
mort <- lapply(mort, function(x) x[,-c(1,2)])

for (i in seq_along(mort)) {
  writeData(planti, sheet = sheet1[[i]],
            x = mort[[i]],
            startRow = 21, startCol = 3,
            colNames = FALSE, rowNames = FALSE)
}

# =========================================================
# 10. ESPERANZA DE VIDA – TABULADO (1 DECIMAL)
# =========================================================
mort1 <- comp[,c(1,2,12,10,11)] %>%
  pivot_longer(c(3:5), names_to = "indicador", values_to = "value") %>%
  pivot_wider(names_from = "year", values_from = "value") %>%
  setDT()

mort1 <- redondear_1(mort1)
mort1 <- split(mort1, mort1$prov)
mort1 <- lapply(mort1, function(x) x[,-c(1,2)])

for (i in seq_along(mort1)) {
  writeData(planti, sheet = sheet1[[i]],
            x = mort1[[i]],
            startRow = 24, startCol = 3,
            colNames = FALSE, rowNames = FALSE)
}

# =========================================================
# 11. MIGRACIÓN (2 DECIMALES)
# =========================================================
mig <- comp[,c(1,2,5,9)] %>%
  pivot_longer(c(3:4), names_to = "indicador", values_to = "value") %>%
  pivot_wider(names_from = "year", values_from = "value") %>%
  setDT()

mig <- redondear_2(mig)
mig <- split(mig, mig$prov)
mig <- lapply(mig, function(x) x[,-c(1,2)])

for (i in seq_along(mig)) {
  writeData(planti, sheet = sheet1[[i]],
            x = mig[[i]],
            startRow = 28, startCol = 3,
            colNames = FALSE, rowNames = FALSE)
}

# =========================================================
# 12. GUARDAR SALIDA FINAL
# =========================================================
saveWorkbook(planti,
             "out/tabul_indica_demogra_prov_1990-35.xlsx",
             overwrite = TRUE)

# ============================ FIN =========================

